// src/models/patientsModel.js
const db = require('../utils/db');

async function getPatients(page, limit) {
  try {
    // 查询总记录数
    const [countResult] = await db.query(`SELECT COUNT(*) AS count FROM patients`);
    const totalCount = countResult[0].count;

    // 计算偏移量
    const offset = (page - 1) * limit;

    // 查询分页数据
    const [rows] = await db.query(
      `SELECT 
        id,
        patient_id, 
        name, 
        gender, 
        age, 
        phone_number, 
        id_number, 
        DATE_FORMAT(birth_date, '%Y-%m-%d') AS birth_date,
        remark,
        address
      FROM 
        patients
      ORDER BY 
        id DESC
      LIMIT ?, ?`,
      [offset, limit]
    );

 
    return {
      code: 0,
      msg: '',
      count: totalCount,
      data: rows
    };
  } catch (error) {
    console.error(error);
    throw new Error('Failed to fetch patients data.');
  }
}

async function createPatient(patient) {
  const { patient_id, name, gender, age, phone_number, id_number, birth_date,remark, address } = patient;
  const [result] = await db.query(
    'INSERT INTO patients (patient_id, name, gender, age, phone_number, id_number, birth_date,remark, address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
    [patient_id, name, gender, age, phone_number, id_number, birth_date, remark ,address]
  );
  return result.insertId;
}

async function updatePatient(id, patient) {
  // 构建 SET 子句
  const setClauses = Object.entries(patient)
    .map(([key, value]) => `${key} = ?`)
    .join(', ');

  // 如果没有可更新的字段，则抛出错误
  if (!setClauses) {
    throw new Error('No fields to update');
  }

  // 构建查询参数数组
  const queryParams = [...Object.values(patient), id];

  // 构建完整的 SQL 更新语句
  const sql = `UPDATE patients SET ${setClauses} WHERE id = ?`;

  await db.query(sql, queryParams);
}


async function deletePatient(id) {
  await db.query('DELETE FROM patients WHERE id = ?', [id]);
}

module.exports = {
  getPatients,
  createPatient,
  updatePatient,
  deletePatient
};